 # -*- coding: utf-8 -*-

import AE
reload( AE)
from AE import *

import Relation
reload( Relation)
from Relation import *

import Attribute
reload( Attribute)
from Attribute import *

import Instance
reload( Instance)
from Instance import *

import db
reload( db)
from db import McfConnector

class Acquisition():
	"""Description of an acquisition"""
	def __init__( self, libmyCF, ac_id, ae_id, type, date, team, comment):
		self.libmyCF = libmyCF
		self.ac_id = ac_id
		self.ae_id = ae_id
		self.type = type
		self.date = date
		self.team = team
		self.comment = comment


	def getInstances( self):
		"""Load all the instances for this acquisition from myCorporisFabrica"""
		result = []
		query="SELECT * FROM Instances WHERE acquisition_id = \"%d\""%( self.ac_id)
		for data in self.libmyCF.connector.mcfQuery(query):
			result.append( Instance( libmyCF=self.libmyCF, instance_id=int(data[0]), ac_id=int(data[1]), ae_id=int(data[2])))
		return result


	def getInstanceOfAE( self, ae):
		"""Return the instance corresponding to the given ae 'ae' for this acquisition or a new one if there is no instance in the database"""
		id = -1
		print "je demande l'instance avec ac: " + str(self.ac_id) + ", ae: " +  str(ae.getId())
		query="SELECT instances_id FROM Instances WHERE acquisition_id = \"%d\" and AE_id = \"%d\""%( self.ac_id, ae.getId())
		for data in self.libmyCF.connector.mcfQuery(query):
			id = int( data[0]) # There is just one instance for a given ae and acquistion
			print "je passe bien par l'identification de l'instance"
		
		# If there no instance for this AE, create a new one
		if id == -1:
			instance = self.libmyCF.acquisitions.addInstance( Instance( libmyCF=self.libmyCF, instance_id=None, ac_id=self.getId(), ae_id=ae.getId()))
			id = instance.getId()
		return self.libmyCF.acquisitions.all_instances[ id ]


	def getAE( self):
		return self.libmyCF.ontology.all_AEs[self.ae_id]


	def getId( self):
		return self.ac_id


	def getName( self):
		return self.getAE().getName()
